from flask import Blueprint,json,request,jsonify
from db import db1
bp_course = Blueprint("course",__name__)
#接口
@bp_course.route('/couponM',methods = ['POST','GET','PUT','DELETE'])
def couponM():
    if request.method =="POST":
        # 获取用户输入
        data = request.data
        if data:  
            data = json.loads(data)
        
        else:
            data = request.form
        
        #构造sql语句
        sql = "insert into coupon values(0,'%s',%d,'%s','%s')"%(data['name'],int(data['total']),data['starttime'],data['endtime'])
        #pymysql
        db1.insert(sql)
        #返回结果
        return 'ok'
    elif request.method=='GET':
        id=request.args.get('id')
       
        if id:
            #构造sql语句
            sql="select * from coupon where id=%d"%(int(id))
            res = db1.find(sql)
            return jsonify({'code':200,'coupon':res})
    elif request.method == "PUT":
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form

        sql="update coupon set name='%s',total=%d,starttime='%s',endtime='%s' where id=%d"%(data['name'],int(data['total']),data['starttime'],data['endtime'],int(data['id']))
        db1.insert(sql)
        return jsonify({"code":200})

    elif request.method == "DELETE":
        # 获取id
        id = request.args.get('id')
        if id:
            #构造sql语句
            sql="delete from coupon where id=%d"%(int(id))
            #调用数据库中insert方法
            db1.insert(sql)
            #返回
            return jsonify({'code':200})